package com.anyikang.volunteer.sos.volunteer.app.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.anyikang.volunteer.sos.volunteer.R;
import com.anyikang.volunteer.sos.volunteer.app.MyApplication;
import com.anyikang.volunteer.sos.volunteer.app.MyConstant;
import com.anyikang.volunteer.sos.volunteer.app.bean.MyCurrentOrder;
import com.anyikang.volunteer.sos.volunteer.app.bean.MyRescueListItem;
import com.anyikang.volunteer.sos.volunteer.app.bean.User;
import com.anyikang.volunteer.sos.volunteer.app.mine.RescueDetailActivity;
import com.anyikang.volunteer.sos.volunteer.app.mine.WriteReportActivity;
import com.anyikang.volunteer.sos.volunteer.utils.CommonUtil;
import com.anyikang.volunteer.sos.volunteer.utils.MyErrorDeal;
import com.anyikang.volunteer.sos.volunteer.utils.okhttputils_callback.StringDialogCallback;
import com.lzy.okhttputils.OkHttpUtils;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

import org.json.JSONObject;

import java.util.List;

import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

/**
 * XW.GAO
 * 我的救援记录适配器
 *
 */
public class MyRescueRecordAdapter extends BaseAdapter {
    private Context mContext;
    private List<MyRescueListItem> mMyRecueRecordList;
    private String mDeviceIMEI;
    String TAG = "MyRescueRecordAdapter";

    public MyRescueRecordAdapter(List<MyRescueListItem> recordList, Context context, String deviceIMEI) {
        this.mContext = context;
        this.mMyRecueRecordList = recordList;
        this.mDeviceIMEI = deviceIMEI;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        int curPos = position;
        MyRescueListItem item = mMyRecueRecordList.get(position);
        ViewHolder holder = null;

        if (convertView == null) {
            // 复用乱序问题
            convertView = LayoutInflater.from(mContext).inflate(R.layout.myrescue_record_item, null);
            holder = new ViewHolder();
            holder.imvPerson = (ImageView) convertView.findViewById(R.id.imvPerson);
            holder.tvName = (TextView) convertView.findViewById(R.id.tvName);
            holder.tvAddress = (TextView) convertView.findViewById(R.id.tvAddress);
            holder.tvSosTime = (TextView) convertView.findViewById(R.id.tvSosTime);
            holder.tvSosState = (TextView) convertView.findViewById(R.id.tvSosState);
            holder.btSureComplete = (Button) convertView.findViewById(R.id.btSureComplete);
            holder.btWriteReport = (Button) convertView.findViewById(R.id.btWriteReport);
            holder.relativeLayoutItem = (RelativeLayout) convertView.findViewById(R.id.relativeLayoutItem);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        int state = item.getState();
        if (state == 2)  //未完成，隐藏写报告按钮
        {
            holder.btSureComplete.setVisibility(View.VISIBLE);
            holder.btWriteReport.setVisibility(View.GONE);
        } else if(state == 3)     //已完成再显示写报告按钮
        {
            holder.btSureComplete.setVisibility(View.GONE);
            holder.btWriteReport.setVisibility(View.VISIBLE);
        }
        else if(state == 4)
        {
            holder.btSureComplete.setVisibility(View.GONE);
            holder.btWriteReport.setVisibility(View.GONE);
        }
        //根据完成状态，来判断显示隐藏按钮tvSosState
        holder.btSureComplete.setOnClickListener(new MyButtonClick(curPos));
        holder.btWriteReport.setOnClickListener(new MyButtonClick(curPos));
        holder.relativeLayoutItem.setOnClickListener(new MyButtonClick(curPos));
        String imageUrl = MyConstant.IMAGE_ADDRESS + item.getImageUrl();


        ImageLoader.getInstance().displayImage(imageUrl, holder.imvPerson, MyApplication.optionsForPerson, new ImageLoadingListener() { //更新服务端的照片
                    @Override
                    public void onLoadingStarted(String imageUri, View view) {

                        Log.i(TAG,"onLoadingStarted");

                    }

                    @Override
                    public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                        Log.i(TAG,"onLoadingFailed");

                    }

                    @Override
                    public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                        Log.i(TAG,"onLoadingComplete");
                       //gxw+如果有重复错位的图片，拿 mViewHolder.headImages.setTag(iconurl);解决
                    }

                    @Override
                    public void onLoadingCancelled(String imageUri, View view) {
                        Log.i(TAG,"onLoadingCancelled");

                    }
                }

        );





        String name = item.getName();
        String address = item.getAddress();

        if (!TextUtils.isEmpty(name))
        {
            holder.tvName.setText(name);
        }
        if (!TextUtils.isEmpty(address))
        {
            holder.tvAddress.setText(address);
        }

        long sosTime = item.getSosTime();
        String strSosTime = String.valueOf(sosTime+"");
        String strSosTime2 = CommonUtil.getDateTimeYmdHms(Long.parseLong(strSosTime));
        if(!TextUtils.isEmpty(strSosTime2))
        {
            holder.tvSosTime.setText(strSosTime2);
        }
        return convertView;
    }

    @Override
    public int getCount() {
        return mMyRecueRecordList.size();
    }

    @Override
    public Object getItem(int position) {
        return mMyRecueRecordList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    class ViewHolder {
        ImageView imvPerson;
        TextView tvName;
        TextView tvAddress;
        TextView tvSosTime;
        TextView tvSosState;

        Button btWriteReport;
        Button btSureComplete;

        RelativeLayout relativeLayoutItem;
        //gxw-TextView tvSosState;
    }

    public class MyButtonClick implements View.OnClickListener
    {
        public int mPosition;

        public  MyButtonClick(int position)
        {
            mPosition = position;
            return;
        }

        /**
         * 告诉服务端，确认完成
         */
        public void sureComplete()
        {
            User user = new User(mContext);
            String token = user.getUserToken();
            String orderId = mMyRecueRecordList.get(mPosition).getOrderId();

            Log.i(TAG,"url ="+ MyConstant.API_SURE_COMPLETE + "token="+token+",orderId="+orderId);
            OkHttpUtils
                    .post(MyConstant.API_SURE_COMPLETE)//
                    .tag(MyConstant.API_SURE_COMPLETE)//
                    .params("tokenId", token)//
                    .params("orderId",orderId)
                    .execute(new StringDialogCallback((Activity) mContext) {
                        @Override
                        public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {

                            int retCode = response.code();
                            if(retCode == 200)
                            {
                                Log.i(TAG,"onSuccess 200 return："+s);
                                try
                                {
                                    JSONObject sureCompleteJson = new JSONObject(s);

                                    if(sureCompleteJson.getInt("status") == 1)//确认成功
                                    {
                                        MyCurrentOrder currentOrder = new MyCurrentOrder();
                                        currentOrder.sureComplete(mContext);
                                        mMyRecueRecordList.get(mPosition).setState(3);
                                        MyApplication.isRecvingOrder = false;
                                        notifyDataSetChanged();

                                    }
                                    else {
                                        String msg = sureCompleteJson.getString("msg");
                                        MyErrorDeal.dealError(msg,mContext);
                                    }
                                }
                                catch (Exception e)
                                {
                                    e.printStackTrace();
                                }
                            }
                            else
                            {
                                MyErrorDeal.dealHttpError(response,mContext);
                                Log.i(TAG,"onSuccess "+retCode+"return: "+s);
                            }
                        }

                        @Override
                        public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {

                            MyErrorDeal.dealHttpError(response,mContext);

                        }
                    });
        }

        @Override
        public void onClick(View view) {
            switch (view.getId())
            {
                case R.id.btSureComplete:
                    sureComplete();

                    break;
                case R.id.btWriteReport:  //写报告
                    Intent i = new Intent(mContext, WriteReportActivity.class);
                    i.putExtra("orderId",mMyRecueRecordList.get(mPosition).getOrderId());
                    mContext.startActivity(i);
                    break;
                case R.id.relativeLayoutItem:
                    Intent i2 = new Intent(mContext, RescueDetailActivity.class);
                    i2.putExtra("orderId",mMyRecueRecordList.get(mPosition).getOrderId());
                    mContext.startActivity(i2);
                    break;
            }

        }
    }


}